package cn.goktech.controller;

import cn.goktech.util.ResultUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

/**
 * @ClassName FreemarkerVeiwController
 * @Discription TODO
 * @Author Carter
 * @Date 2021/4/20 17:48
 * @Version 1.0
 **/
@Controller
@RequestMapping("/page")
public class FreemarkerVeiwController {

    @Autowired
    ServletContext servletContext;
    @RequestMapping("/test")
    public String Test(Model model, HttpServletRequest request) {
        Writer out = new StringWriter();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "" + request.getContextPath() + "/";
        //将页面路径通过model传给前台
        model.addAttribute("basePath", basePath);
        //通过HttpServletRequest 获取url中的值，如code值
        String code = request.getParameter("code");
        //将获取的code参数传给前台
        model.addAttribute("code ", code);

        Configuration configuration = new Configuration();
        configuration.setServletContextForTemplateLoading(servletContext,"/");
        try {
            // 获取模板,并设置编码方式
            Template template = configuration.getTemplate("test.ftl");
            template.setEncoding("utf-8");
            // 合并数据模型与模板
            template.process(model, out); //将合并后的数据和模板写入到流中，这里使用的字符流
            out.flush();

        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toString();
    }
}
